package com.mes.handler;

import com.basis.utils.BaseServletHandler;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.dal.service.OBDal;
import org.openbravo.model.common.plm.Product;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

//上传产品图纸绑定在物料上
public class ProductDrawingHandler  extends BaseServletHandler {

	private String p_id;
	
	@Override
	protected JSONObject service(HttpServletRequest request, HttpServletResponse response) {
		
		p_id = "";
		p_id = request.getParameter("WmlmNameId");
		
		JSONObject result = new JSONObject();
		
		try {
			result.put("desc", "系统繁忙，请稍后再试。");
			result.put("result", false);
			request.setCharacterEncoding("utf-8");
			
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室
			factory.setSizeThreshold(1024 * 1024);
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			// 可以上传多个文件
			List<FileItem> listItem = (List<FileItem>) upload.parseRequest(request);
			
			for(FileItem item : listItem){
				if (item.getName() == null || "".equals(item.getName().trim())) {
					// 不含文件内容
					continue;
				}
				//定义一个存储路径
				//String savePath = request.getSession().getServletContext().getRealPath("/upload");
				String  savePath = "D:\\JavaTool\\photo";
				File file = new File(savePath);
				
				if(!file.exists() && !file.isDirectory()){
					file.mkdir();
				}
				
				String fileName =  item.getName();
				
				if(fileName.endsWith(".pdf") || fileName.endsWith(".png") || fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")){

					fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
					
					InputStream in = item.getInputStream();
					
					Product products = OBDal.getInstance().get(Product.class, p_id);
					
					//判断该工序是否已经上传，如果已经上传就删除原上传的pdf文件
					if(products.getDrawingPath() != null){
						File f = new File(products.getDrawingPath());
						f.delete();
					}
					
					//时间戳
				    long Pix = System.currentTimeMillis();
				    String filePix = Pix + "";
				
				    String oldPix = fileName.substring(fileName.lastIndexOf("."),fileName.length()); 
				    fileName = fileName.substring(0,fileName.lastIndexOf("."));
				    fileName = fileName + filePix + oldPix;
					FileOutputStream out = new FileOutputStream(savePath+ "\\" + fileName);
					
					//创建一个缓冲区
					byte buffer[] = new byte[1024];
					//判断输入流中的数据是否已经读完的标识
					int len = 0;
					//循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
					while((len=in.read(buffer))>0){
						//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
						out.write(buffer, 0, len);
					}
					//关闭输入流
					in.close();
					//关闭输出流
					out.close();
					
					products.set("uploaded", "OK");
					products.set("drawingPath", savePath+ "\\" + fileName);
					products.set("drawingName", item.getName());
					OBDal.getInstance().save(products);
					OBDal.getInstance().commitAndClose();
					result.put("desc", "上传成功！");
					result.put("result", true);
					return result;
					
					
				}else{
					result.put("desc", "只允许图片格式的文件上传！");
					result.put("result", false);
					return result;
					
				}
			
			}
			
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
		}

		return result;
		}	
}
	
